package com.layton.PubSub;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer_PubSub {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2.设置连接参数
        factory.setHost("127.0.0.1");//默认值为localhost
        factory.setPort(5672);//默认值为5672
        factory.setVirtualHost("/layton");//虚拟机默认为/
        factory.setUsername("layton");//guest
        factory.setPassword("layton");//guest
        //3.获取对应连接connection
        Connection connection = factory.newConnection();
        //4.创建channel
        Channel channel = connection.createChannel();
        //5.创建交换机
        /**
         * String exchange, BuiltinExchangeType type, boolean durable, boolean autoDelete, boolean internal, Map<String, Object> arguments
         * exchange 交换机名称
         * type 交换机的类型 四种 direct定向 fanout广播 topic通配符 headers参数匹配
         * durable 是否持久化
         * autoDelete 是否自动删除
         * internal 是否内部使用
         * arguments 参数列表
         */
        String exchangeName = "test_fanout";
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.FANOUT,true,false,false,null);
        //6.创建队列
        String queue1Name = "test_fanout_queue1";
        String queue2Name = "test_fanout_queue2";
        channel.queueDeclare(queue1Name,true,false,false,null);
        channel.queueDeclare(queue2Name,true,false,false,null);
        //7.绑定队列和交换机
        /**
         * queue 队列名称
         * exchange 交换机名称
         * routingKey 路由键,绑定规则 如果交换机类型为fanout,则设置为空
         */
        channel.queueBind("test_fanout_queue1","test_fanout","");
        channel.queueBind("test_fanout_queue2","test_fanout","");
        //8.发送消息
        String body = "日志信息:张三调用了findAll方法...日志级别error...";
        channel.basicPublish(exchangeName,"",null,body.getBytes());
        //9.释放资源
        channel.close();
        connection.close();
    }
}
